<template>
  <div class="clientType">
    <div class="title-container">
      <div class="left-box">
        <el-form ref="form" :model="searchForm" :inline="true" class="formClass">
          <el-form-item>
            <el-input
              prefix-icon="el-icon-search"
              type="input"
              clearable
              placeholder="请输入客户名称"
              v-model="searchForm.customerName"
              @clear="clearSearch"
              style="margin-right: 10px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <global-card>
      <template #leftTitle>
        <perButton label="新建客户" type="primary" icon="el-icon-plus" perms="PROTOCOL_ADD"
                   @click="newCompanyClick"></perButton>
        <el-button type="success" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </template>
      <template #content>
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          class="elTable"
        >
          <el-table-column type="index" label="序号" width="80" align="center"/>
          <el-table-column prop="customerCode" label="客户编码" align="center"/>
          <el-table-column prop="customerName" label="客户名称" align="center"/>
          <el-table-column prop="customerPhone" label="客户手机号" align="center"/>
          <el-table-column prop="housekeeperCode" label="管家编号" align="center"/>
          <el-table-column prop="housekeeperName" label="管家名称" align="center"/>
          <el-table-column prop="customerBirthday" label="客户生日" align="center"/>
          <el-table-column prop="memberLevelRuleName" label="会员等级" align="center"/>
          <el-table-column prop="grandTotalAmount" label="累计充值金额" align="center"/>
          <el-table-column prop="remainingAmount" label="当前余额" align="center"/>
          <el-table-column label="操作" width="280" align="center">
            <template #default="{ row }">
              <perButton label="绑定管家" type="primary" size="mini" perms="PROTOCOL_EDIT"
                         @click="handlerBind(row)"></perButton>
              <perButton label="编辑" type="warning" size="mini" perms="PROTOCOL_EDIT"
                         @click="handlerEdit(row)"></perButton>
              <perButton label="删除" type="danger" size="mini" perms="PROTOCOL_DEL"
                         @click="handlerDelete(row)"></perButton>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <pagination
          class="pagination"
          :total="count"
          :page.sync="pageIndex"
          :limit.sync="pageSize"
          @pagination="pagination"
        />
      </template>
    </global-card>

    <!--  新增编辑  -->
    <yc-dialog
      ref="ycDialog"
      :dialogTitle="dialogTitle"
      :centerTitle="dialogCenterTitle"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            :model="newModel"
            :rules="rules"
            ref="newModelRef"
            label-width="110px"
          >
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="newModel.customerName"/>
            </el-form-item>
            <el-form-item label="客户手机号" prop="customerPhone">
              <el-input v-model="newModel.customerPhone" type="number"/>
            </el-form-item>
            <el-form-item label="客户生日" prop="customerBirthday">
              <el-date-picker
                v-model="newModel.customerBirthday"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!--  绑定管家  -->
    <yc-dialog
      ref="bindDialog"
      :dialogTitle="dialogTitle"
      :show-center="false"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            :model="newBindModel"
            :rules="rulesBind"
            ref="bindModelRef"
            label-width="110px"
          >
            <el-form-item label="绑定管家" prop="housekeeperCode">
              <el-select v-model="newBindModel.housekeeperCode">
                <el-option
                  v-for="item in majordomoData"
                  :key="item.housekeeperCode"
                  :label="item.housekeeperName"
                  :value="item.housekeeperCode"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogBindSave">确定</el-button>
        <el-button @click="$refs.bindDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import {
    queryPageCustomer,
    insertCustomer,
    updateCustomer,
    deleteCustomer,
    bindHouseKeeper
  } from "@/api/clientInfoManagement/client"
  import {
    queryListMajordomo
  } from "@/api/majordomoManagement/majordomoInfo"
  import { getToken } from "@/utils/auth"

  export default {
    components: {
      ycDialog,
      perButton
    },
    data() {
      return {
        tableData: [],
        pageIndex: 1,
        pageSize: 10,
        count: 0,
        searchForm: {
          customerName: ""
        },
        itemTableData: {},
        detailsDisabled: false,
        isGlobalMessageShow: false,

        dialogCenterTitle: "",
        dialogTitle: "",
        message: "",

        loading: false,
        newModel: {
          id: "",
          customerCode: "",
          customerName: "",
          customerPhone: "",
          customerBirthday: ""
        },
        rules: {
          customerName: [
            { required: true, message: "请输入客户名称", trigger: "blur" }
          ],
          customerPhone: [
            { required: true, message: "请输入客户手机号", trigger: "blur" }
          ],
          customerBirthday: [
            { required: true, message: "请选择客户生日", trigger: "change" }
          ]
        },
        headers: {
          token: getToken()
        },
        upload: "/uploadManager/upload",
        newBindModel: {
          housekeeperCode: ""
        },
        rulesBind: {
          housekeeperCode: [
            { required: true, message: "请选择管家", trigger: "change" }
          ]
        },
        majordomoData: [],
        addOrUpdateLoading: false
      }
    },
    created() {
      this.getData()
    },
    methods: {
      async searchClick() {
        this.getData()
      },
      clearSearch() {
        this.getData()
      },
      async getData() {
        const { customerName } = this.searchForm
        this.loading = true
        const data = await queryPageCustomer({
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          customerName
        })
        this.tableData = data.object.data
        this.count = data.object.count
        this.loading = false
      },
      pagination(pageItem) {
        this.getData(pageItem.page, pageItem.limit)
      },


      handlerDelete({ id }) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const { status } = await deleteCustomer({
            id
          })
          if (status == 200) {
            this.getData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      // 新建客户
      newCompanyClick() {
        this.dialogCenterTitle = "新建客户"
        this.dialogTitle = "新建客户"

        Object.keys(this.newModel).forEach((item) => {
          this.newModel[item] = ""
        })

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true
        if (this.$refs["newModelRef"]) {
          this.$refs["newModelRef"].clearValidate()
        }
      },
      handlerEdit(row) {
        this.dialogCenterTitle = "编辑客户"
        this.dialogTitle = "编辑客户"

        this.newModel = {
          id: row.id,
          customerCode: row.customerCode,
          customerName: row.customerName,
          customerPhone: row.customerPhone,
          customerBirthday: row.customerBirthday
        }

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
        if (this.$refs["newModelRef"]) {
          this.$refs["newModelRef"].clearValidate()
        }
      },

      async dialogSave() {
        this.$refs.newModelRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true

            if (this.newModel.id) {
              //  编辑
              const { status, message } = await updateCustomer({
                ...this.newModel
              })
              if (status == 200) {
                this.$message({
                  message: message,
                  type: "success"
                })
                this.getData()
                this.$refs.ycDialog.dialogVisible = false
              }
            } else {
              const { status, message } = await insertCustomer({ ...this.newModel })
              if (status == "200") {
                this.$message({
                  message: message,
                  type: "success"
                })
                this.getData()
                this.$refs.ycDialog.dialogVisible = false
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      // 绑定管家
      handlerBind(row) {
        this.dialogTitle = "绑定管家"

        this.itemTableData = row
        this.newBindModel.housekeeperCode = row.housekeeperCode
        this.queryListMajordomo()

        this.$refs.bindDialog.dialogVisible = true
      },
      async queryListMajordomo() {
        const data = await queryListMajordomo({})
        this.majordomoData = data.object
      },
      dialogBindSave() {
        this.$refs.bindModelRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            const { status, message } = await bindHouseKeeper({
              housekeeperCode: this.newBindModel.housekeeperCode,
              customerCode: this.itemTableData.customerCode
            })
            if (status == "200") {
              this.$message({
                message: message,
                type: "success"
              })
              this.getData()
              this.$refs.bindDialog.dialogVisible = false
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      receive() {
        this.isGlobalMessageShow = false
      },

      refresh() {
        this.searchForm = {
          agreementName: "",
          agreementType: ""
        }
        this.getData()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .clientType {
    .title-container {
      display: flex;
      justify-content: flex-end;
      margin-right: 20px;

      .left-box {
        display: flex;

        .formClass {
          /*display: flex;*/
          /*margin-right: 20px;*/

          .el-form-item {
            margin-top: 20px;
            margin-bottom: 0;

            .el-input {
              width: 216px;
            }

            .el-select {
              width: 171px;
              margin-left: 10px;
            }

            .el-date-editor {
              width: 336px;
              margin-left: 10px;
            }
          }
        }

        /*.el-button {*/
        /*  // width: 42px;*/
        /*  height: 36px;*/
        /*  margin-top: 20px;*/
        /*}*/
      }
    }
  }
</style>
